package org.pz.wrapper;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.Map;

/**
 * 转换实体类
 * */
public class BeanWrapperUtil {

    public static <T> T mapToEntity(Map<String, Object> map, Class<T> entityClass) {
        try {
            T entity = entityClass.getDeclaredConstructor().newInstance();
            BeanWrapper beanWrapper = new BeanWrapperImpl(entity);
            map.forEach((key, value) -> {
                // 如果存在该属性且可写，则赋值
                if (beanWrapper.isWritableProperty(key)) {
                    beanWrapper.setPropertyValue(key, value);
                }
            });
            return entity;
        } catch (Exception e) {
            throw new RuntimeException("Map 转实体类失败", e);
        }
    }

}
